package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.DTO.InsertComboCardConfigBO;
import com.ruoyi.common.core.domain.DTO.SelectComboCardConfigBO;
import com.ruoyi.common.core.domain.DTO.SelectComboCardConfigVO;
import com.ruoyi.common.core.domain.DTO.UpdateComboCardConfigBO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.ComboCardConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/combo/card")
public class ComboCardConfigController {
    @Autowired
    private ComboCardConfigService comboCardConfigService;
    @PostMapping("/insert")
    public AjaxResult insertComboCardConfig(@RequestBody @Validated InsertComboCardConfigBO insertComboCardConfigBO) {
        comboCardConfigService.insertComboCardConfig(insertComboCardConfigBO);
        return AjaxResult.success();
    }

    @PostMapping("/update")
    public AjaxResult updateComboCardConfig(@RequestBody @Validated UpdateComboCardConfigBO updateComboCardConfigBO) {
        comboCardConfigService.updateComboCardConfig(updateComboCardConfigBO);
        return AjaxResult.success();
    }

    @PostMapping("/list")
    public AjaxResult selectComboCardConfigList(@RequestBody @Validated SelectComboCardConfigBO selectComboCardConfigBO) {
        return AjaxResult.success(comboCardConfigService.selectPurchaseRecord(selectComboCardConfigBO));
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, SelectComboCardConfigBO selectComboCardConfigBO) {
        String fileName = null;
        try {
            fileName = URLEncoder.encode("套餐卡号数据.xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        List<SelectComboCardConfigVO> list = comboCardConfigService.exportComboCardConfig(selectComboCardConfigBO);
        if(ObjectUtils.isEmpty(list)){
            throw new BusinessException("导出数据为空");
        }
        ExcelUtil<SelectComboCardConfigVO> util = new ExcelUtil<SelectComboCardConfigVO>(SelectComboCardConfigVO.class);
        util.exportExcel(response, list, "卡号和卡密");
    }
}
